package com.example.caloriedaily

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.app.PendingIntent.getActivity
import android.content.Intent
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.icu.util.Calendar
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


class MainActivity : AppCompatActivity() {
    lateinit var beginDate: String
    lateinit var endDate: String


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    //跳转页面
    fun edit(view: View) {
        val intent = Intent(this, Main2Activity::class.java)
        startActivity(intent)
    }

    //选择日期
    @RequiresApi(Build.VERSION_CODES.N)
    fun click(view: View) {
        when (view.id) {
            R.id.begin -> {
                // 日期选择器
                val ca = Calendar.getInstance()
                var mYear = ca[Calendar.YEAR]
                var mMonth = ca[Calendar.MONTH]
                var mDay = ca[Calendar.DAY_OF_MONTH]

                val datePickerDialog = DatePickerDialog(
                    this,
                    DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                        mYear = year
                        mMonth = month
                        //格式对齐
                        mDay = dayOfMonth
                        var mDate = ""
                        if (mMonth < 9) {
                            mDate = "${year}-0${month + 1}-${dayOfMonth}"
                        }
                        if (dayOfMonth < 10) {
                            mDate = "${year}-${month + 1}-0${dayOfMonth}"
                        }
                        if (dayOfMonth < 10 && mMonth < 9) {
                            mDate = "${year}-0${month + 1}-0${dayOfMonth}"
                        }
                        if (dayOfMonth >= 9 && mMonth >= 10) {
                            mDate = "${year}-0${month + 1}-0${dayOfMonth}"
                        }
                        // 将选择的日期赋值给TextView
                        begin.text = mDate
                        beginDate = mDate.toString()
                    },
                    mYear, mMonth, mDay
                )
                datePickerDialog.show()
            }
            R.id.end -> {
                // 日期选择器
                val ca = Calendar.getInstance()
                var mYear = ca[Calendar.YEAR]
                var mMonth = ca[Calendar.MONTH]
                var mDay = ca[Calendar.DAY_OF_MONTH]

                val datePickerDialog = DatePickerDialog(
                    this,
                    DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                        mYear = year
                        mMonth = month
                        mDay = dayOfMonth
                        //格式对齐
                        mDay = dayOfMonth
                        var mDate = ""
                        if (mMonth < 9) {
                            mDate = "${year}-0${month + 1}-${dayOfMonth}"
                        }
                        if (dayOfMonth < 10) {
                            mDate = "${year}-${month + 1}-0${dayOfMonth}"
                        }
                        if (dayOfMonth < 10 && mMonth < 9) {
                            mDate = "${year}-0${month + 1}-0${dayOfMonth}"
                        }
                        if (dayOfMonth >= 9 && mMonth >= 10) {
                            mDate = "${year}-0${month + 1}-0${dayOfMonth}"
                        }
                        // 将选择的日期赋值给TextView
                        end.text = mDate
                        endDate = mDate
                    },
                    mYear, mMonth, mDay
                )
                datePickerDialog.show()
            }
        }
    }

    @SuppressLint("RestrictedApi")
    @RequiresApi(Build.VERSION_CODES.O)
    fun query(view: View) {
        if (this.begin == null || this.end == null) {
            // 日期其中一个为空，不渲染
        }
        if (this.beginDate > this.endDate) {
            //当开始日期大于结束日期，不渲染
        } else {
            val graph = findViewById<GraphView>(R.id.graph)
            graph.removeAllSeries()
            // 根据日期时间段查找数据记录，然后渲染
            val data = loadData()

            //数据类型转换并放进dataPointList列表
            Log.i("data", data.toString())
            val dataPointList = ArrayList<DataPoint>()
            for (i in data) {
                dataPointList.add(
                    DataPoint(
                        SimpleDateFormat("yyyy-MM-dd").parse(i.mdate),
                        i.mvalue.toDouble()
                    )
                )
            }
            Log.i("dataPointList", dataPointList.toString())
            // 图表数据数组
            val dataPoint: Array<DataPoint> = dataPointList.toTypedArray()
            Log.i("dataPoint", dataPoint.toString())
            Log.i("渲染图表[]size => ", dataPoint.size.toString())
            Log.i("渲染图表[]", "加载数据完毕")
            // 把数据数组作为折线渲染数据
            val series: LineGraphSeries<DataPoint> = LineGraphSeries(dataPoint)
            // 渲染到图表
            graph.addSeries(series)

            graph.gridLabelRenderer.labelFormatter = DateAsXAxisLabelFormatter(this)
            graph.gridLabelRenderer.numHorizontalLabels = dataPoint.size

            //图表X轴设置
            graph.viewport.setMinX(dataPoint[0].x)
            graph.viewport.setMaxX(dataPoint[dataPoint.size - 1].x)
            // set manual x bounds to have nice steps
            graph.viewport.isXAxisBoundsManual = true

            // as we use dates as labels, the human rounding to nice readable numbers
            // is not necessary
            graph.gridLabelRenderer.setHumanRounding(true)

            Log.i("渲染图表[]", "渲染数据完毕")
        }
    }

    //查询beginDate和endDate之间的数据并放到result数组中
    private fun loadData(): ArrayList<Record> {
        Log.i("加载函数[]", "拉取数据记录")
        val dbHelper = DBHelper(this, "mydb", 1)
        // 取得一个只读的数据库对象
        val db: SQLiteDatabase = dbHelper.readableDatabase
        // 查询结果，最多4条
        val cursor: Cursor = db.rawQuery(
            "select * from notes where time >= ? and time <= ? limit 4",
            arrayOf(beginDate, endDate)
        )
        Log.i("加载函数[]", "定义结果数组")
        // 结果数组
        val result = arrayListOf<Record>()
        Log.i("拿到的数据条数", cursor.count.toString())
        // 拿出数据放到result中
        Log.i("加载函数[]", "查询结果遍历")

        val c = cursor.count
        if (c > 0) {
            while (cursor.moveToNext()) {
                //获取日期和数值(0：nid，1：time，2：content)
                val d = cursor.getString(1)
                val v = cursor.getString(2)
                val n = Record(d, v)
                // 加到result
                result.add(n)
                Log.i("加载函数[]", "结果集add一个对象")
                //日志打印输出
                Log.i("result[]", "query date => " + n.mdate)
                Log.i("result[]", "query value => " + n.mvalue)
                Log.i("result[]", "query obj => " + cursor.toString())
            }
        }
        Log.i("加载函数[]", "返回结果")
        return result
    }

}